package com.framework.loippi.controller.api;

import com.framework.loippi.api.core.GenericAPIController;
import com.framework.loippi.api.utils.ApiUtils;
import com.framework.loippi.api.utils.Xerror;
import com.framework.loippi.cache.ConfigCache;
import com.framework.loippi.entity.*;
import com.framework.loippi.service.*;
import com.framework.loippi.service.weixin.impl.WxBaseServiceImpl;
import com.framework.loippi.support.APIPrincipal;
import com.framework.loippi.support.FileInfo.FileType;
import com.framework.loippi.tencent.IM.CloudSignUtils;
import com.framework.loippi.utils.*;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import io.swagger.annotations.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Controller - 通用
 *
 * @author caisz
 * @version 1.0
 */
@Controller
@RequestMapping("/api/common")
@Api(value = "通用接口", description = "通用接口", tags = {"通用模块"})
public class CommonController extends GenericAPIController {

    @Resource
    private RedisService redisService;

    @Resource
    private AreaService areaService;

    @Resource
    private ArticleService articleService;

    @Resource
    private AppService appService;

    @Resource
    private AdService adService;

    @Resource
    private FeedbackService feedbackService;

    @Resource(name = "fileServiceImpl")
    private FileService fileService;

    @Resource
    private SystemMessageService messageService;


    @Resource
    private com.framework.loippi.utils.qiniu.FileService qiniuFileService;
    @Resource
    private ParameterSettingService parameterSettingService;
    @Resource
    private WxBaseServiceImpl wxBaseService;

    /**
     * 发送短信验证码： 向第三方发送短信验证码
     *
     * @param mobile 手机号
     * @param type   1-注册 2-登录 3-忘记密码 4绑定验证原手机号 5微信绑定手机号 6 验证新手机号 7
     * @return
     */
    @ApiOperation(value = "发送短信验证码： 向第三方发送短信验证码", response = String.class, notes = "发送短信验证码： 向第三方发送短信验证码", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", required = true, paramType = "query", value = "手机号"),
            @ApiImplicitParam(name = "type", required = true, paramType = "query", value = "1-注册 2-登录 3-忘记密码 4更换绑定手机号 5微信绑定手机号6 验证新手机号")
    })
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})//响应码
    @RequestMapping(value = "/msg.json", method = {RequestMethod.POST})
    public @ResponseBody
    String msg(HttpServletResponse response, String mobile, Integer type) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("text/html;charset=UTF-8");
//        if (null == mobile || "".equals(mobile)) {
//            return ApiUtils.error("手机号不能为空");
//        }
//        if (type == 1 && null != appUser) {
//            return ApiUtils.error("该账号已存在");
//        }
//        if (type == 2 && null == appUser) {
//            return ApiUtils.error("该账号未注册");
//        }
//        if (type == 3 && null == appUser) {
//            return ApiUtils.error("该账号不存在");
//        }
        if (type == 4) {
//            if (!StringUtils.isNullOrEmpty(appUser)) {
//                if (!mobile.equals(appUser.getPhone())) {
//                    return ApiUtils.error("原手机号错误");
//                }
//            } else {
//                return ApiUtils.error("该账号不存在");
//            }
        }
//		if (type == 5 && !StringUtils.isNullOrEmpty(appUser)) {
//			return ApiUtils.error("账号已被绑定");
//		}
//        if (type == 6 && !StringUtils.isNullOrEmpty(appUser)) {
//            return ApiUtils.error("该手机号已被绑定");
//        }
//        String code = RandomStringUtils.random(6, "0123456789");
		String code = "123456";
        String param = JsonUtils.toJson(Paramap.create().put("code", code));
//        boolean sms = AlidayuSmsPlugin.sendSMS(mobile, "SMS_171118855", "爱仓", param);
//        if (!sms) {
//            return ApiUtils.error("验证码发送失败");
//        }
        redisService.save(mobile, code, 300);
        return ApiUtils.success();
    }


    @ApiOperation(value = "获取参数配置项", notes = "", response = String.class, httpMethod = "POST", produces = "application/html")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "配置key", required = true, paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    @RequestMapping(value = "/get_parameter_setting.json", method = RequestMethod.POST)
    @ResponseBody
    public String getParameterSetting(String key) {
        String value = parameterSettingService.find(key);
        return ApiUtils.success(value != null ? value : "");
    }

    /**
     * 帮助文章/系统文章详情
     *
     * @return
     */
    @ApiOperation(value = "客服电话", notes = "", response = String.class, httpMethod = "POST", produces = "application/html")
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    @RequestMapping(value = "/platform_phone.json", method = RequestMethod.POST)
    @ResponseBody
    public String platformPhone() {
        ParameterSetting parameterSetting = parameterSettingService.find(1L);
        return ApiUtils.success(parameterSetting.getAValue());
    }

    /**
     * 帮助文章/系统文章详情
     *
     * @param id
     * @param model
     * @return
     */
    @ApiOperation(value = "帮助文章/系统文章详情", notes = "返回h5页面(16-关于我们,17-注册协议,22-隐私政策,23-联系我们，24-选择推荐人说明25-拼团说明26消费红包说明27推广注册公报说明28推广红包说明29推广商家红包说明30-用户协议32-分销规则)", httpMethod = "GET", produces = "application/html")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "文章id", required = true, paramType = "query")
    })
    @RequestMapping(value = "/article/view/{id}.jhtml", method = RequestMethod.GET)
    public String artivleView(@PathVariable(value = "id") Long id, ModelMap model) {
        Article article = articleService.find(id);
        model.addAttribute("article", article);
        return "/api/article_view";
    }


    /**
     * 消息详情
     *
     * @param id
     * @param model
     * @return
     */
    @ApiOperation(value = "消息详情", notes = "把{id}换成消息的id", httpMethod = "GET", produces = "application/html")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "文章id", required = true, paramType = "query")
    })
    @RequestMapping(value = "/message/view/{id}.jhtml", method = RequestMethod.GET)
    public String messageView(@PathVariable(value = "id") Long id, ModelMap model) {
//        UserMessage userMessage = userMessageService.findMessage(id);
//        userMessage.setStatus(1);
//        userMessageService.update(userMessage);
//        model.addAttribute("article", userMessage);
        return "/api/article_view";
    }

    /**
     * 判断验证码是否正确
     *
     * @return
     */
    @ApiOperation(value = "判断验证码是否正确", produces = "application/json", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, paramType = "query"),
            @ApiImplicitParam(name = "code", value = "短信验证码", required = true, paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败"),
    })
    @RequestMapping(value = "/check_phone.json", method = RequestMethod.POST)
    @ResponseBody
    public String checkCode(String phone, String code) {
        if (StringUtils.isNullOrEmpty(phone)) {
            return ApiUtils.error("请填写手机号");
        }
        String msgCode = redisService.get(phone, String.class);
        if (StringUtils.isNullOrEmpty(msgCode) || StringUtils.isNullOrEmpty(code) || !msgCode.equals(code)) {
            return ApiUtils.error("验证码错误");
        }
        return ApiUtils.success();
    }

    /**
     * 帮助中心文章列表
     */
    @ApiOperation(value = "帮助中心文章列表", notes = "", httpMethod = "POST", produces = "application/json", response = Article.class, responseContainer = "List")
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功", response = Article.class, responseContainer = "List"), @ApiResponse(code = 0, message = "操作失败")})
    @RequestMapping(value = "/article/list.json", method = RequestMethod.POST)
    public @ResponseBody
    String list(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        map.put("isShow", 1);
        //Page<Article> page = articleService.findByPage(pageable);
        List<Article> list = articleService.findList(map);
        return ApiUtils.success(list);
    }

    /**
     * 文章详情
     */
    @RequestMapping(value = "/article.json", method = RequestMethod.POST)
    @ApiOperation(value = "文章详情", notes = "", httpMethod = "POST", produces = "application/json", response = Article.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "文章Id", required = true, paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    public @ResponseBody
    String article(Long id, HttpServletRequest request) {
        Article article = articleService.find(id);
        return ApiUtils.success(article);
    }


    /**
     * 版本检测
     */
    @RequestMapping(value = {"/version.json"}, method = RequestMethod.POST)
    @ApiOperation(value = "版本检测", httpMethod = "POST", response = App.class, produces = "application/json")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "device", value = "设备0-ios 1-安卓", required = true, paramType = "query"),
    })
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    public @ResponseBody
    String check(Integer device, HttpServletRequest request, String version) {
        //参数验证
        if (StringUtils.isEmpty(version)) {
            return ApiUtils.error(Xerror.PARAM_INVALID);
        }
        App app = appService.find("device", device);
        if (app.getVersion().equalsIgnoreCase(version)) {
            return ApiUtils.error("20001", "暂无更新");
//			app.setUpdate("No");
//			return ApiUtils.success(app);
        } else if (version.compareTo(app.getVersion()) < 0) {
            app.setUpdate("Yes");
            return ApiUtils.success(app);
        }

        app.setUpdate("No");
        return ApiUtils.success(app);
    }


    /**
     * 上传 ---返回相对路径
     */
    @RequestMapping(value = "/upload.json", method = RequestMethod.POST)
    @ApiOperation(value = "上传图片", httpMethod = "POST", notes = "上传图片file文件流 fileType 为字符串(image, file, media, flash)", produces = "application/json", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileType", value = "文件类型", paramType = "query", dataType = "file"),
            @ApiImplicitParam(name = "file", value = "file文件流", required = true, paramType = "query"),
    })
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    public @ResponseBody
    String upload(FileType fileType, MultipartFile file, HttpServletResponse response) {
        if (!fileService.isValid(fileType, file)) {
            return ApiUtils.error("文件类型不正确");
        } else {
            String url = fileService.uploadLocal(fileType, file);
            if (url == null) {
                return ApiUtils.error();
            } else {
                return ApiUtils.success(url);
            }
        }
    }


    /**
     * 上传图片到七牛云
     */
    @RequestMapping(value = "/upload_to_qiniu.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "上传图片到七牛云", httpMethod = "POST", notes = "上传图片file文件流", produces = "application/json", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "file文件流", required = true, paramType = "query", dataType = "file"),
    })
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    public @ResponseBody
    String uploadToQiniu(@RequestParam(value = "file") MultipartFile file, HttpServletResponse response) {
        Configuration config = new Configuration(Region.region2());

        UploadManager uploadManager = new UploadManager(config);
        Auth auth = Auth.create(ConfigCache.getConfig("qiniu.accessKey"), ConfigCache.getConfig("qiniu.secretKey"));
        String filename = UUID.randomUUID().toString();
        try {
//			CommonsMultipartFile cf = (CommonsMultipartFile) file;
//			DiskFileItem fi = (DiskFileItem) cf.getFileItem();
            uploadManager.put(file.getInputStream(), file.getSize(), filename, auth.uploadToken(ConfigCache.getConfig("qiniu.bucket")), null, null, false);
        } catch (QiniuException e) {
            e.printStackTrace();
            return ApiUtils.error();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = ConfigCache.getConfig("qiniu.url").concat(filename);
        if (url == null) {
            return ApiUtils.error();
        } else {
            return ApiUtils.success(url);
        }
    }


    /**
     * 上传图片到七牛云
     */
    @RequestMapping(value = "/upload_files_to_qiniu.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "多文件上传图片到七牛云", httpMethod = "POST", notes = "上传图片file文件流", produces = "application/json", response = String.class, responseContainer = "List")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "files", value = "file文件流", required = true, paramType = "File", dataType = "file", allowMultiple = true),
    })
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    public @ResponseBody
    String uploadFilesToQiniu(@RequestParam MultipartFile[] files, HttpServletResponse response) {
        Configuration config = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(config);
        Auth auth = Auth.create(ConfigCache.getConfig("qiniu.accessKey"), ConfigCache.getConfig("qiniu.secretKey"));
        String url = null;
        String filename = null;
        List<String> urls = new ArrayList<>();
        try {
//			CommonsMultipartFile cf = (CommonsMultipartFile) file;
//			DiskFileItem fi = (DiskFileItem) cf.getFileItem();
            for (MultipartFile file : files) {
                filename = UUID.randomUUID().toString();
                uploadManager.put(file.getInputStream(), file.getSize(), filename, auth.uploadToken(ConfigCache.getConfig("qiniu.bucket")), null, null, false);
                url = ConfigCache.getConfig("qiniu.url").concat(filename);
                urls.add(url);
            }
        } catch (QiniuException e) {
            e.printStackTrace();
            return ApiUtils.error();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (url == null) {
            return ApiUtils.error();
        } else {
            return ApiUtils.success(urls);
        }
    }


    /**
     * base64上传到七牛云
     */
    @RequestMapping(value = "/base64_upload_to_qiniu.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ApiOperation(value = "上传图片到七牛云base64", httpMethod = "POST", notes = "上传图片file文件流 fileType 为字符串", produces = "application/json", response = String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "base64String", value = "bse64字符串", required = true, paramType = "form"),
    })
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    public @ResponseBody
    String uploadBase64ToQiniu(String base64String, HttpServletResponse response) {
        MultipartFile file = BASE64DecodedMultipartUtils.base64ToMultipart(base64String);
        Configuration config = new Configuration(Region.region2());

        UploadManager uploadManager = new UploadManager(config);
        Auth auth = Auth.create(ConfigCache.getConfig("qiniu.accessKey"), ConfigCache.getConfig("qiniu.secretKey"));
        String filename = UUID.randomUUID().toString();
        try {
            uploadManager.put(file.getBytes(), filename, auth.uploadToken(ConfigCache.getConfig("qiniu.bucket")));
//			uploadManager.put(file.getInputStream(), file.getSize(), filename, auth.uploadToken(QINIU_TOKEN), null, null, false);
        } catch (QiniuException e) {
            e.printStackTrace();
            return ApiUtils.error();
        } catch (IOException e) {
            e.printStackTrace();
            return ApiUtils.error();
        }
        String url = ConfigCache.getConfig("qiniu.url").concat(filename);
        if (StringUtils.isEmpty(url)) {
            return ApiUtils.error();
        } else {
            return ApiUtils.success(url);
        }
    }


    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    private APIPrincipal getPrincipal(HttpServletRequest request) {
        String authentication = request.getHeader(APIPrincipal.PORPERTITY_AUTHENTICATION);
        if (null == authentication || "".equals(authentication)) {
            // 获取回话ID
            authentication = request.getParameter(APIPrincipal.PORPERTITY_AUTHENTICATION);
        }
        // 获取缓存实体
        APIPrincipal principal = redisService.get(authentication, APIPrincipal.class);
        return principal;
    }

    /**
     * APP端广告列表
     */
    @RequestMapping(value = {"/advertise.json"}, method = RequestMethod.POST)
    @ApiOperation(value = "app端广告列表", httpMethod = "POST", notes = "", produces = "application/json", response = Ad.class, responseContainer = "List")
    @ApiResponses({@ApiResponse(code = 1, message = "操作成功"), @ApiResponse(code = 0, message = "操作失败")})
    public @ResponseBody
    String advertise() {
        List<Ad> list = adService.findList("type", 1);
        return ApiUtils.success(list);
    }

    /**
     * 获取七牛Token
     */
    @RequestMapping(value = {"/qiniu/getToken.json"}, method = RequestMethod.POST)
    @ApiOperation(value = "获取七牛Token", responseContainer = "Map", response = String.class, httpMethod = "POST", produces = "application/json")
    public @ResponseBody
    String qiniu_token() {
        Map<String, Object> map = new HashMap<>();
        Auth auth = Auth.create(ConfigCache.getConfig("qiniu.accessKey"), ConfigCache.getConfig("qiniu.secretKey"));
        String token = auth.uploadToken(ConfigCache.getConfig("qiniu.bucket"));
        map.put("token", token);
        map.put("domain", ConfigCache.getConfig("qiniu.url"));
        map.put("prefix", ConfigCache.getConfig("qiniu.prefix"));
        return ApiUtils.success(map);
    }


    /**
     * 获取七牛Token
     */
    @RequestMapping(value = {"/get_province.json"}, method = RequestMethod.POST)
    @ApiOperation(value = "获取所有省", response = Area.class, httpMethod = "POST", produces = "application/json")
    public @ResponseBody
    String allProvince() {
        List<Area> roots = areaService.findRoots();
        return ApiUtils.success(roots);
    }


    /**
     * 获取分享微信参数
     *
     * @param request
     * @return
     */
    @ApiOperation(value = "获取微信参数", notes = "", httpMethod = "POST", produces = "application/json")
    @ApiResponses({
            @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败")
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "param", value = "分享的参数值 为1是直接传入链接地址 2传入商品id 3传入拼团里面的id, 4传入设计师id", required = true, paramType = "query")
    })
    @RequestMapping(value = "/getWexinConfig.json", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String getSign(HttpServletRequest request, String param) {
        String nonceStr = RandomUtils.getRandomString(16);
        long timestamp = (System.currentTimeMillis()) / 1000;
        String signature = wxBaseService.getJsSignature(nonceStr, timestamp, param);
        String appId = ConfigCache.getConfig("wx.mp.appId");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nonceStr", nonceStr);
        map.put("timestamp", timestamp);
        map.put("signature", signature);
        map.put("appId", appId);
        return ApiUtils.success(map);
    }

    /**
     * 获取IM登录凭证
     *
     * @param im im账号
     * @return
     */
    @ApiOperation(value = "获取IM登录凭证", notes = "返回Map usersig 为签名", httpMethod = "POST", produces = "application/json")
    @ApiImplicitParam(name = "im", value = "账号", paramType = "query", required = true)
    @ApiResponses({
            @ApiResponse(code = 1, message = "操作成功"),
            @ApiResponse(code = 0, message = "操作失败")
    })
    @RequestMapping(value = "/getUserSig.json", method = RequestMethod.POST)
    @ResponseBody
    public String getUserSig(String im) {
        String sign = CloudSignUtils.genSig(im, 604800);
        return ApiUtils.success(Paramap.create().put("usersig", sign));
    }

}
